package com.yuexunit.account.service;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.yuexunit.account.action.v2.model.VerifyCodeType;
import com.yuexunit.account.entity.VerifyCodeEntity;
import com.yuexunit.core.exception.NoPermissionException;
import com.yuexunit.core.exception.NotFoundException;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.persist.PersistUtil;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.util.DateUtil;


/**
 * @author wangjinshui
 */
@Implements(VerifyCodeService.class)
public class VerifyCodeServiceImpl implements VerifyCodeService {
	private SmsService smsService = ComponentFactory.loadClass(SmsService.class);
	
	
	@Override
	public void sendVerifyCode(VerifyCodeType type, String accountName) {
		String verifyCode = createVerifyCode(type, accountName);
		
		String content = "";
		switch(type) {
			case REGISTER: content = String.format("(51wangzhen)注册验证码%s, 60分钟内输入有效，立即注册。", verifyCode);
				
				break;
			case FOGET_PASSWORD: content = String.format("(51wangzhen)忘记密码验证码%s, 60分钟内输入有效，立即登录。", verifyCode);
				break;
			case CHANGE_MOBILE: content = String.format("(51wangzhen)修改手机验证码%s, 60分钟内输入有效。", verifyCode);
				break;
			default: 
				break;
		}
		
		smsService.sendSms(accountName, content, type);
	}
	
	@Transactional
	public String createVerifyCode(VerifyCodeType type, String accountName) {
		VerifyCodeEntity entity = new VerifyCodeEntity(accountName, type);
		PersistUtil.insert(entity);
		
		return entity.getVerifyCode();
	}

	
	@Override
	public void checkVerifyCode(VerifyCodeType type, String mobile, String verifyCode) {
		boolean result = false;
		
		try {
			VerifyCodeEntity existed = inquireVerifyCode(type, mobile);
			
			result = existed.getExpireDate().after(DateUtil.now()) && existed.getVerifyCode().equals(verifyCode);
		} catch(Exception ignore) {
		}
		
		if (result == false) {
			throw new NoPermissionException("校验码错误");
		}
	}
	
	private VerifyCodeEntity inquireVerifyCode(VerifyCodeType type, String mobile) {
		DetachedCriteria cri = DetachedCriteria.forClass(VerifyCodeEntity.class);
		cri.add(Restrictions.eq("accountName", mobile))
			.add(Restrictions.eq("type", type))
			.addOrder(Order.desc("expireDate"))
			;
		
		List<VerifyCodeEntity> entityList = PersistUtil.get(cri);
		if (entityList.isEmpty()) {
			throw new NotFoundException("验证码不存在");
		}
		
		return entityList.get(0);
	}
}
